﻿using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using LitJson;
using UnityEngine;
using AnimationParamerPair = System.Collections.Generic.KeyValuePair<string, int >;
namespace abilities
{
    // 该类包含了如何改变动画的信息(状态、参数)
    public class AnimationRule
    {
        public int alpha;
        public int animationType;
        public string additionalAnim;
        public List<AnimationParamerPair> animationParams;

        public void FromJsonAnimation(LitJson.JsonData value)
        {
            alpha = value.ContainsKey("alpha") ? (int)value["alpha"] : 255;
            animationType = (int)value["animationType"];
            additionalAnim = value.ContainsKey("additionalAnim") ? (string)value["additionalAnim"] : "";

            animationParams = new();
            if (value.ContainsKey("animationParams"))
            {
                var arr = value["animationParams"];
                foreach (JsonData i in arr)
                {
                    string name = i.Keys.First();
                    int val = (int)i[name];//arr[i];
                    animationParams.Add(new(name,val));
                }
            }
        }
    
        public void Apply(UnitObject target)
        {
            int alpha = this.alpha;
            // 动画参数和它们的新值。倒转设置为-1。
            List<AnimationParamerPair> animationParameters = this.animationParams;
            // 附加视觉效果会在单位上徘徊，直到效果消失。
            string additionalAnimation = this.additionalAnim;
            if (alpha != 255)
            {
            	target.GetComponent<Renderer>().material.DOFade(alpha,0.35f);
            }
            string animationType = "anim_"+this.animationType;
            if (!string.IsNullOrEmpty(animationType))
            {
            	target.GetComponentInChildren<Animator>().SetTrigger(animationType);
            }
            
            foreach(var pair in animationParameters)
            {
                target.GetComponentInChildren<Animator>().SetInteger(pair.Key, pair.Value);
            }
            
            if (!string.IsNullOrEmpty(additionalAnimation))
            {
                //附加动画
            }
        }

        public void Cancel(UnitObject target)
        {
            // 动画参数和它们的新值。倒转设置为-1。
            List<AnimationParamerPair> animationParameters = this.animationParams;
            // 附加视觉效果会在单位上徘徊，直到效果消失。
            string additionalAnimation = this.additionalAnim;
            target.GetComponent<Renderer>().material.DOFade(255,0.35f);
            foreach(var pair in animationParameters)
            {
                target.GetComponentInChildren<Animator>().SetInteger(pair.Key, 1);
            }
            
            if (!string.IsNullOrEmpty(additionalAnimation))
            {
                //移除附加动画
            }
        }
    }
}